//
//  StudentQuestionsViewController.m
//  SrnTeacher
//
//  Created by iDeneb on 6/19/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "SrnTeacherAppDelegate.h"
#import "StudentQuestionsViewController.h"
#import "QuartzCore/QuartzCore.h"

#define ROW_HEIGHT 60
@implementation StudentQuestionsViewController
@synthesize myscrollView,viewData;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	myscrollView.layer.cornerRadius = 8;
	myscrollView.layer.masksToBounds = YES;
	viewData = [[SrnTeacherAppDelegate App].udb getViewByNum:-1];
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (IBAction)clear:(id)sender {
	[viewData removeAllObjects];
	[[SrnTeacherAppDelegate App].udb deleteOneQuestion:-1];
	[self.view setNeedsDisplay];
	[myscrollView reloadData];}

- (IBAction)done:(id)sender {
    [self dismissModalViewControllerAnimated:YES];
    //if ([delegate respondsToSelector:@selector(setupViewController:didFinishSetupWithInfo:)]) {
    //    [delegate setupViewController:self didFinishSetupWithInfo:setupInfo];
    //}
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    viewData = [[SrnTeacherAppDelegate App].udb getViewByNum:-1];
	NSLog(@"sections count, %hu", [viewData count]);
	return [viewData count];
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return 2;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier1 = @"header";
	static NSString *CellIdentifier2 = @"tail";
	UITableViewCell *cell= nil;
	int rr = indexPath.row;
    if(indexPath.row % 2 == 0) {
		cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
		if (cell == nil) {
			cell = [self tableViewCellWithReuseIdentifier:CellIdentifier1 forIndexPath:indexPath];
		}
	 } else {
		cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
		 if (cell == nil) {
			 cell = [self tableViewCellWithReuseIdentifier:CellIdentifier2 forIndexPath:indexPath];
		 }
	}
	 
	

	
	// configureCell:cell forIndexPath: sets the text and image for the cell -- the method is factored out as it's also called during minuted-based updates.
	//[self configureCell:cell forIndexPath:indexPath];
    
    // Set up the cell...
	//User *cellValue = [[shouji138AppDelegate App].listOfItems objectAtIndex:indexPath.row];
	//cell.text = cellValue.username;
	
    return cell;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark -
#pragma mark Configuring table view cells

#define NAME_TAG 1
#define TIME_TAG 2
#define IMAGE_TAG 3
#define QUES_TAG 4

#define LEFT_COLUMN_OFFSET 10.0
#define LEFT_COLUMN_WIDTH 120.0

#define MIDDLE_COLUMN_OFFSET 130.0
#define MIDDLE_COLUMN_WIDTH 200.0

#define RIGHT_COLUMN_OFFSET 200.0

#define MAIN_FONT_SIZE 18.0
#define LABEL_HEIGHT 26.0

#define IMAGE_SIDE 30.0

- (UITableViewCell *)tableViewCellWithReuseIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath{
	
	/*
	 Create an instance of UITableViewCell and add tagged subviews for the name, local time, and quarter image of the time zone.
	 */
	
	UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
	
	/*
	 Create labels for the text fields; set the highlight color so that when the cell is selected it changes appropriately.
	 */
	
	
	int index = indexPath.section;
	User *cellValue;
	int rindex = indexPath.row;
	
	cellValue = [viewData objectAtIndex:index];
	
	if ([identifier localizedCompare:@"header"] == 0) {
		UILabel *label;
		CGRect rect;
		rect = CGRectMake( LEFT_COLUMN_OFFSET, (ROW_HEIGHT - IMAGE_SIDE) / 2.0, 100, IMAGE_SIDE);
		//label = [[UILabel alloc] initWithFrame:rect];
		UIButton *viewButton = [[UIButton alloc] initWithFrame:rect];
		viewButton.tag = TIME_TAG;
		
        [viewButton setImage:[UIImage imageNamed:@"Clear.png"] forState:UIControlStateNormal];	
		//[viewButton setBackgroundColor:[UIColor grayColor]];
		[viewButton addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
		[viewButton setTag:index];	
		[cell.contentView addSubview:viewButton];
		[viewButton release];
		
		rect = CGRectMake( MIDDLE_COLUMN_OFFSET, (ROW_HEIGHT - IMAGE_SIDE) / 2.0, 100, LABEL_HEIGHT);	
		label = [[UILabel alloc] initWithFrame:rect];
		label.tag = NAME_TAG;
		label.font = [UIFont boldSystemFontOfSize:MAIN_FONT_SIZE];
		label.adjustsFontSizeToFitWidth = YES;
		
		label.highlightedTextColor = [UIColor whiteColor];
		
		//for(NSInteger i=0;i<[cell.contentView.subviews count];i++){
//			UIView * subView = [cell.contentView.subviews objectAtIndex:i];
//			NSInteger subViewTag = [subView tag];
//			NSLog(@"view tags: %hu , %hu", i, subViewTag);
//		}
		
	    label.text = cellValue.username;
		[cell.contentView addSubview:label];
		[label release];
		
	} else {
		UILabel *label;
		CGRect rect;
		rect = CGRectMake( LEFT_COLUMN_OFFSET, (ROW_HEIGHT - IMAGE_SIDE) / 2.0, 200, LABEL_HEIGHT);	
		label = [[UILabel alloc] initWithFrame:rect];
		label.tag = QUES_TAG;
		label.font = [UIFont boldSystemFontOfSize:MAIN_FONT_SIZE];
		label.adjustsFontSizeToFitWidth = YES;
		
		label.highlightedTextColor = [UIColor whiteColor];
		NSString *question = cellValue.choice;
		label.text = question;
		[cell.contentView addSubview:label];
	    [label release];
	}

	
	return cell;
}


- (void)configureCell:(UITableViewCell *)cell forIndexPath:(NSIndexPath *)indexPath {
    
	
	//if (rindex % 2 == 0) {
//			
//	} else {
//		UILabel *label;
//		label = (UILabel *)[cell.contentView viewWithTag:QUES_TAG];
//		NSString *question = cellValue.choice;
//		//if (cellValue.choice.length > 30) {
//		//	NSMutableString *ms = [[NSMutableString alloc] initWithCapacity:150];
//		//	NSArray *listTokens = [cellValue.choice componentsSeparatedByString:@" "];
//		 //   for(int i =0 ; i < [listTokens count]; i++) {
//		//		NSString * cc =  (NSString *)[listTokens objectAtIndex:i];
//		//		[ms appendString:cc];
//		//		if ([ms length ] > 30 *(i+1)) {
//		//			[ms appendString:@"\n"];
//		//		}
//		//	}
//       //     question = [NSString stringWithString: ms];
//		//}
//	    label.text = question;		
//	}
	

}    
- (IBAction)clickAction:(id)sender {
	UIButton* viewButton = (UIButton *)sender;
	NSLog(@"one question button Clear clicked!");
    int cid = [viewButton tag];
    if([viewData count] > cid) {
	  User *ur = [viewData objectAtIndex:cid];
	  NSString *name = ur.username;
	  NSString *ask = ur.choice;
	  [[SrnTeacherAppDelegate App].udb deleteOneAsk:name choiceStr:ask];
	  //viewData = [[SrnTeacherAppDelegate App].udb getViewByNum:-1];
	  //[self.view setNeedsDisplay];
	  [viewData removeObjectAtIndex:cid];
	}
	[myscrollView reloadData];	
}

- (void) viewWillAppear:(BOOL)animated{
	NSLog(@"student question view will appear");
	[myscrollView reloadData];
	[self.view setNeedsDisplay];
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end
